package paytreasure.controller;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;


import com.alibaba.fastjson.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import paytreasure.po.Accountdetail;
import paytreasure.service.BillService;
import paytreasure.util.ConstantUtil;
import paytreasure.util.ObjAnalysis;
import paytreasure.util.OrderNumber;
import paytreasure.util.pag.Page;
import paytreasure.vo.ResilrAccountdetail;
import paytreasure.vo.ResultPagVo;
import paytreasure.vo.ResultVo;


@Controller
@RequestMapping("/bill")
public class BillController {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(BillController.class);
	
	@Resource
	private BillService billService;
	
	private ResultVo result;
	
	
	/**
	 * 新增保存
	 * */
	@RequestMapping(value="/saveBill",method = {RequestMethod.POST},produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String saveBill(@RequestBody HashMap<String, Object> map) {
		Accountdetail accountdetail = new Accountdetail();
		try {
//			DateTimeConverter dtConverter = new DateTimeConverter();  
//            ConvertUtilsBean convertUtilsBean = new ConvertUtilsBean();  
//            convertUtilsBean.deregister(Date.class);  
//            convertUtilsBean.register(dtConverter, Date.class);  
//            BeanUtilsBean beanUtilsBean = new BeanUtilsBean(convertUtilsBean,new PropertyUtilsBean());
//            beanUtilsBean.populate(accountdetail, map);
			
            ObjAnalysis.transMap2Bean(map, accountdetail);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LOGGER.error("保存账单信息失败！类型转化异常");
		} 
		accountdetail.setBillId(UUID.randomUUID().toString());
		accountdetail.setCreateTime(new Date());
		
		if("1".equals(accountdetail.getIcon())) {
			
			Date createDate = accountdetail.getCreateDate();
			String date = new SimpleDateFormat("yyyyMMdd").format(createDate);
			accountdetail.setOrders(date+OrderNumber.getOrders());
			accountdetail.setMerchantOrder("T200P1" + OrderNumber.getMerOrder());//淘宝
		}
		
		if("2".equals(accountdetail.getIcon())) {//余额宝
			Date createDate = accountdetail.getCreateDate();
			String date = new SimpleDateFormat("yyyyMMdd").format(createDate);
			accountdetail.setOrders(date+OrderNumber.getYorders());
		}
		
		if("3".equals(accountdetail.getIcon())) {
			Date createDate = accountdetail.getCreateDate();
			String date = new SimpleDateFormat("yyyyMMdd").format(createDate);
			accountdetail.setOrders(date+OrderNumber.getOrders());
			accountdetail.setMerchantOrder("T100P3" +  OrderNumber.getMerOrder());//联通
		}
		
		result = billService.saveBill(accountdetail);
		return JSONObject.toJSONString(result, ConstantUtil.vFilter);
	}
	
	/**
	 * 修改保存
	 * */
	@RequestMapping(value="/editBill",method = {RequestMethod.POST},produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String editBill(@RequestBody HashMap<String, Object> map) {
		Accountdetail accountdetail = new Accountdetail();
		try {
			//BeanUtils.populate(accountdetail, map);
			ObjAnalysis.transMap2Bean(map, accountdetail);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			LOGGER.error("修改账单信息失败！类型转化异常");
		}
		result = billService.updateBill(accountdetail);
		return JSONObject.toJSONString(result, ConstantUtil.vFilter);
	}
	
	/**
	 * 账单列表分页查询
	 * */
	@RequestMapping(value="/queryBill",method = {RequestMethod.POST},produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String queryBill(@RequestBody HashMap<String, String> map) {
		Page page = null;
		//查询月份
		int totalCount = billService.getCount(map);
		page = new Page(totalCount, Integer.parseInt(map.get("pageNow") == null ? "1"
				: map.get("pageNow")));
		
		if(totalCount == 0){
			result = new ResultVo(ConstantUtil.RESULT_SUCCESS,
					"数据库没有数据！", new ArrayList<Accountdetail>());
			return JSONObject.toJSONString(result, ConstantUtil.vFilter);
		}
		map.put("startPos", String.valueOf(page.getStartPos()));
		map.put("pageSize", String.valueOf(page.getPageSize()));
		map.put("hasnext", String.valueOf(page.gethasNext()));
		result = billService.getCondition(map);
		
		ResultPagVo pagVo = new ResultPagVo();
		pagVo.setResultCode(result.getResultCode());
		pagVo.setResultMsg(result.getResultMsg());
	    TreeMap<String, List<ResilrAccountdetail>> map1 = new TreeMap<String, List<ResilrAccountdetail>>();
	    if(result.getResultObj() == null){
	    	pagVo.setResultObj(map1);
	    }else{
	    	pagVo.setResultObj(result.getResultObj());
	    }
		
		pagVo.setResultPage(page);
		
//		if(result.getResultObj() != null){
//			Map resultMap = (Map)result.getResultObj();
//			Set<Object> set = resultMap.keySet();
//			pagVo.setResultSet(set);
//		}
		return JSONObject.toJSONString(pagVo, ConstantUtil.vFilter);
		
	}
	
	/**
	 * 账单修改页面查询
	 * */
	
	@RequestMapping(value="/queryBillById",method = {RequestMethod.POST},produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String queryBillById(@RequestBody HashMap<String, String> map,
			HttpServletResponse response) {
		result = billService.getById(map.get("billId"));
		return JSONObject.toJSONString(result, ConstantUtil.vFilter);
	}
	
	@RequestMapping(value="/getYear",method = {RequestMethod.POST},produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getYear() {
		Map<String, Object> map = new HashMap<String, Object>();
		//年
		List<String> yearList = new ArrayList<String>();
		for (int i = 2017; i < 2100; i++) {
			String year = i + "年";
			yearList.add(year);
		}
		map.put("year", yearList);
		//月
		List<String> mouthList = new ArrayList<String>();
		for (int i = 1; i < 13; i++) {
			String mouth = "";
			if(i<10){
				mouth = "0" + i + "月";
			}else{
				mouth = i + "月";
			}
			mouthList.add(mouth);
		}
		map.put("mouth", mouthList);
		//日
		List<String> dayList = new ArrayList<String>();
		for (int i = 1; i < 32; i++) {
			String day = "";
			if(i<10){
				day = "0" + i + "日";
			}else{
				day = i + "日";
			}
			dayList.add(day);
		}
		map.put("day", dayList);
		//时
		List<String> hourList = new ArrayList<String>();
		for (int i = 0; i < 24; i++) {
			String hour = "";
			if(i<10) {
				hour = "0" + i + "时";
			}else{
				hour = i + "时";
			}
			hourList.add(hour);
		}
		map.put("hour", hourList);
		//分
		List<String> minuteList = new ArrayList<String>();
		for (int i = 0; i < 60; i++) {
			String minute = i + "分";
			if(i<10) {
				minute = "0" + i + "分";
			}else{
				minute = i + "分";
			}
			minuteList.add(minute);
		}
		map.put("minute", minuteList);

		result = new ResultVo(ConstantUtil.RESULT_SUCCESS, "获取成功", map);
		return JSONObject.toJSONString(result, ConstantUtil.vFilter);
	}

}
